import React, { Component } from "react";
import {
  View,
  Text,
  TouchableWithoutFeedback,
  TouchableOpacity,
  FlatList
} from "react-native";
import { Avatar, Button, Icon, ThemeProvider } from "react-native-elements";
import moment from "moment";
import CustomHeader from "../../components/CustomHeader";
import { getBgColorByType, getTColorByType, hexToReverse } from "../../utils";
import request from "../../utils/request";
import { MyButton } from "../../components/MyButton";

class Record extends Component {
  constructor(props) {
    super(props);
    this.state = {
      personList: [],
      loading: false
    };
  }

  componentDidMount = () => {
    this.focusListener = this.props.navigation.addListener("didFocus", _ => {
      this.getPersonList();
    });
  };
  componentWillUnmount() {
    this.focusListener.remove();
  }

  getPersonList = () => {
    this.setState({ loading: true });
    request(
      "person/list",
      {},
      personList => {
        if (
          JSON.stringify(personList) != JSON.stringify(this.state.personList)
        ) {
          this.setState({ personList, loading: false });
        } else {
          this.setState({ loading: false });
        }
      },
      _ => this.setState({ loading: false })
    );
  };

  renderRecordItem = (showType, recordItem, index) => {
    const { navigation } = this.props;
    return (
      <TouchableOpacity
        key={index}
        style={{
          backgroundColor: getBgColorByType(recordItem.RType),
          margin: 3,
          paddingLeft: 3,
          paddingRight: 3,
          borderRadius: 3
        }}
        onPress={_ =>
          navigation.navigate("AddRecord", {
            pId: recordItem.PId,
            itemId: recordItem.Id
          })
        }
      >
        <Text
          style={{
            color: getTColorByType(recordItem.RType)
          }}
        >
          {moment(recordItem.RecordTime).format("HH:mm") +
            " " +
            (showType ? recordItem.RType : "") +
            (recordItem.Remark ? "(" + recordItem.Remark + ")" : "")}
        </Text>
      </TouchableOpacity>
    );
  };

  renderRecordList = (name, recordList) => {
    return (
      <View
        style={{
          display: "flex",
          flexDirection: "row",
          flexWrap: "wrap",
          alignSelf: "flex-start",
          marginTop: 6,
          alignItems: "center"
        }}
      >
        <Text>{name}:</Text>
        {recordList.length == 0 ? (
          <Text>无</Text>
        ) : (
          recordList.map(this.renderRecordItem.bind(this, name == "其他"))
        )}
      </View>
    );
  };

  renderItem = ({ item, index }) => {
    const { navigation } = this.props;
    let now = moment();
    let birthday = moment(item.Birthday);
    let years = now.diff(birthday, "years");
    birthday.add(years, "years");
    let months = now.diff(birthday, "months");
    birthday.add(months, "months");
    let days = now.diff(birthday, "days");
    let age = "";
    if (years > 0) {
      age += years + "岁";
    }
    if (months > 0) {
      age += months + "月";
    }
    if (days > 0) {
      age += days + "天";
    }
    let 合计 = "";
    let 奶粉 = 0;
    let 纸尿裤 = 0;
    let 大便 = 0;
    let 小便 = 0;

    let 建议 = "";
    let 上次喝奶粉时间 = "";
    let 上次换纸尿裤时间 = "";
    for (let i = 0; i < item.RecordList.length; i++) {
      let recordItem = item.RecordList[i];
      if (recordItem.RType == "奶粉") {
        奶粉 += parseInt(recordItem.Remark);
        if (!上次喝奶粉时间) {
          上次喝奶粉时间 = recordItem.RecordTime;
        }
      }
      if (recordItem.RType == "纸尿裤") {
        纸尿裤++;
        if (!上次换纸尿裤时间) {
          上次换纸尿裤时间 = recordItem.RecordTime;
        }
      }
      if (recordItem.RType == "大便") {
        大便++;
      }
      if (recordItem.RType == "小便") {
        小便++;
      }
    }
    if (奶粉 && 奶粉 != "0") {
      合计 += " 喝奶粉: " + 奶粉 + "ml.";
    }
    if (纸尿裤) {
      合计 += " 换纸尿裤: " + 纸尿裤 + "次.";
    }
    if (大便) {
      合计 += " 大便: " + 大便 + "次.";
    }
    if (小便) {
      合计 += " 小便: " + 小便 + "次.";
    }

    if (上次喝奶粉时间) {
      建议 +=
        " 下次喝奶粉: " +
        (
          (奶粉 / 24) *
          (moment().diff(moment(上次喝奶粉时间)) / 1000 / 60 / 60)
        ).toFixed(0) +
        "ml.";
    }
    if (上次换纸尿裤时间) {
      建议 +=
        " 下次换纸尿裤: " +
        moment(上次换纸尿裤时间)
          .add(24 / 纸尿裤, "hour")
          .format("HH:mm");
    }

    let breastMilk = [],
      milkPowder = [],
      diaper = [];
    other = [];
    for (let i = 0; i < item.RecordList.length; i++) {
      let recordItem = item.RecordList[i];
      switch (recordItem.RType) {
        case "母乳":
          breastMilk.push(recordItem);
          break;
        case "奶粉":
          milkPowder.push(recordItem);
          break;
        case "纸尿裤":
          diaper.push(recordItem);
          break;
        default:
          other.push(recordItem);
          break;
      }
    }

    return (
      <TouchableWithoutFeedback
        onPress={_ => navigation.navigate("AddPerson", { itemId: item.Id })}
      >
        <View
          style={{
            padding: 10,
            borderBottomWidth: 1,
            borderBottomColor: "#d9d9d9"
          }}
        >
          <View
            style={{
              display: "flex",
              flexDirection: "row"
            }}
          >
            <Avatar source={{ uri: item.Avatar }} rounded size="medium" />
            <View
              style={{
                flex: 1,
                marginLeft: 10
              }}
            >
              <Text
                style={{
                  fontSize: 16,
                  fontWeight: "bold"
                }}
              >
                {item.Name}
              </Text>
              <Text style={{ marginTop: 6 }}>{age}</Text>
            </View>
            <MyButton
              icon={<Icon name="add" color="white" />}
              onPress={_ => navigation.navigate("AddRecord", { pId: item.Id })}
            />
          </View>
          {this.renderRecordList("母乳", breastMilk)}
          {this.renderRecordList("奶粉", milkPowder)}
          {this.renderRecordList("纸尿裤", diaper)}
          {this.renderRecordList("其他", other)}
          <View
            style={{
              marginTop: 6
            }}
          >
            <Text>24小时合计: {合计}</Text>
            <Text>建议: {建议}</Text>
          </View>
        </View>
      </TouchableWithoutFeedback>
    );
  };

  render() {
    const { personList, loading } = this.state;
    const { navigation } = this.props;
    return (
      <View
        style={{
          display: "flex",
          flexDirection: "column",
          paddingBottom: 80
        }}
      >
        <CustomHeader
          leftComponent={
            <MyButton
              icon={<Icon name="scan1" type="antdesign" color="white" />}
              onPress={_ => navigation.navigate("ScanScreen")}
            />
          }
          title="喂养记录"
          right="add"
          onRightClick={_ => navigation.navigate("AddPerson")}
        />
        <FlatList
          data={personList}
          onRefresh={this.getPersonList}
          refreshing={loading}
          renderItem={this.renderItem}
        />
      </View>
    );
  }
}

export default Record;
